#
# peerscape.core.iid
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Hexadecimal Information IDs (IIDs)

An IID is a SHA-1 hash naming a dataset.  (It is the hash of the
dataset's root item, excluding the signature.)

Outside of peerscape.core, we generally encode IIDs as hexadecimal
strings and represent binary IIDs as Python buffers.
"""

from binascii import hexlify, unhexlify

def is_iid(x):
    """
    Return True if the argument is a well-formed information ID.

    Either a hexadecimal string or a binary buffer is accepted.

    >>> is_iid('aBcD' * 10)
    True
    >>> is_iid(buffer('\xff' * 20))
    True
    >>> is_iid('abcde')
    False
    >>> is_iid('abcdef')
    False
    >>> is_iid('abcdefg')
    False
    """
    try:
        return len(hex_to_buffer(x)) == 20
    except TypeError:
        return False

def is_canonical_iid(x):
    """
    Return True if the argument is a hexadecimal IID in canonical form.

    >>> is_canonical_iid('abcd' * 10)
    True
    >>> is_canonical_iid('aBcD' * 10)
    False
    >>> is_canonical_iid('wxyz' * 10)
    False
    >>> is_canonical_iid(buffer('\xff' * 20))
    False
    >>> is_canonical_iid('abcd')
    False
    """
    try:
        return (isinstance(x, (str, unicode))
                and len(x) == 40
                and hexlify(unhexlify(x)) == x)
    except TypeError:
        return False

def hex(x):
    """
    Return the argument after checking that it is hexadecimal.

    The return value will always be a byte string and use lower case,
    even if the argument is unicode or includes upper-case letters.

    Furthermore, if the argument is of buffer type, it is interpreted
    as binary data and converted to hexadecimal.

    >>> hex(hex(hex_to_buffer('abcd')))
    'abcd'
    """
    if isinstance(x, buffer):
        return hexlify(x)
    else:
        return hexlify(unhexlify(x))

def hex_to_buffer(x):
    """
    Convert a hexadecimal string to a binary buffer.

    If the argument is already a buffer, it is returned as-is.

    >>> hexlify(hex_to_buffer(hex_to_buffer('abcd')))
    'abcd'
    """
    return x if isinstance(x, buffer) else buffer(unhexlify(x))

if __name__ == '__main__':
    import doctest
    doctest.testmod()
